/**
 * Copyright (c) 2016-Now http://www.javamis.com All rights reserved.
 * No deletion without permission, or be held responsible to law.
 */
package com.javamis.modular.system.controller;

import static com.javamis.common.util.EncryptionUtils.MD5Pwd;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
//import org.springframework.web.bind.annotation.ResponseStatus;

import javax.validation.Valid;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.javamis.common.logger.Logger;
import com.javamis.common.logger.LoggerModule;
import com.javamis.common.logger.LoggerType;
import com.javamis.common.message.Message;
import com.javamis.common.page.PageWarpper;
import com.javamis.modular.system.dao.DepartmentMapper;
import com.javamis.modular.system.dao.DictDataMapper;
import com.javamis.modular.system.dao.UserMapper;
import com.javamis.modular.system.entity.Department;
import com.javamis.modular.system.entity.User;

/**
 * @name:   用户Controller层
 * @version:1.0.2
 * @author:	HuiJia
 * @QQ号： 	763236277
 * @QQ群： 	327773608
 * @邮箱: 	javamis@163.com
 * @site：	http://www.javamis.com
 */
@Controller
@RequestMapping("/user")
@SuppressWarnings("rawtypes")	//抑制单类型警告
public class UserController {
	
	@Autowired
	private UserMapper userMapper;
		
	@Autowired
	DictDataMapper dictDataMapper;
	
	@Autowired
	DepartmentMapper departmentMapper;
	
	@Value("${ims.initPwd}")//从yml配置文件中获取isPreview值是true还是false.
    private String initPwd="123456";
    /**
     * Beetl模板引擎自定义分页标签介绍 
               * 查询用户列表
     */   
    @RequestMapping(value="user_list_bak",method = RequestMethod.GET)
    public String userList(Model model) {
    	return "system/user/user_list";
    }
    
    /**
     * 用户查询列表
     */
    //@RequiresPermissions("user:list")
    @RequestMapping(value = "list",method = RequestMethod.GET)
    public String list(Model model) {
    	return "system/user/list";
    }
    
    @RequestMapping(value = "listData")
    @ResponseBody
    @SuppressWarnings("unlikely-arg-type")
    public PageWarpper<User> listData(User user){
    	PageWarpper<User> pageWarpper = new PageWarpper<User>();
    	IPage<User> page = new Page<>(pageWarpper.getCurrentPage(), pageWarpper.getPageSize());//得到总页数
    	QueryWrapper<User> queryWrapper = new QueryWrapper<>();
    	String sort = pageWarpper.getSortName();
    	String sortOrder =  pageWarpper.getSortOrder();
    	Map<String, Object> queryMap = user.setData(user);
    	if(queryMap.isEmpty() && sort == null) {
    		userMapper.selectPage(page, null);
    	}if(queryMap.isEmpty() && sort != null) {
    		if(sortOrder.equals("desc")) {
    			queryWrapper.orderByDesc(sort);
    		}if(sortOrder.equals("asc")) {
    			queryWrapper.orderByAsc(sort);
    		}
    		userMapper.selectPage(page, queryWrapper);
    	}if(!queryMap.isEmpty()) {
    		 queryWrapper.allEq(queryMap);
    		 userMapper.selectPage(page, queryWrapper);
    	}
    	pageWarpper.setTotal(new Long(page.getTotal()).intValue());
    	List<User> users = page.getRecords();
    	pageWarpper.setRows(users);
    	return  pageWarpper;
    }
    
    
    /**
               * 用户表单页面
     * @param model
     * @return
     */
    //@RequiresPermissions("user:show")
    @RequestMapping(value = "form")
    public String form() {
    	return "system/user/form";
    }
    
    /**
               * 添加用户
     */
    @RequestMapping("/save")
    @ResponseBody
    @Logger(detail = "通过手机号[{{tel}}]获取用户名",level = 3,unit = LoggerModule.USER,type = LoggerType.INSERT)
    public Message<String> save(@Valid User user) {
    	user.setPassword(MD5Pwd(user.getUserCode(),user.getPassword()));
        this.userMapper.insert(user);
        return Message.success("添加用户成功啦!");
    }
    
    /**
                * 根据用户id，修改用户信息
     * @param id
     * @param model
     * @return
     */
    @RequestMapping(value="edit/{id}")
    public String edit(@PathVariable Integer id, Model model) {
    	User user = userMapper.selectById(id);
    	model.addAttribute(user);
    	return "system/user/edit";
    }
    
    /**
               * 修改用户
     */
    @RequestMapping("/edit")
    @ResponseBody
    public Message<String> edit(@Valid User user, BindingResult result) {
    	if(user.getPassword().equals("")) {
    		user.setPassword(MD5Pwd(user.getUserCode(),"123456"));
    	}else {
    		user.setPassword(MD5Pwd(user.getUserCode(),user.getPassword()));
    	}
    	if(user.getDeptId() == 0 && user.getDeptName() != "") {
    		List<Department> deptList =departmentMapper.getDepartmentByName(user.getDeptName());
    		if(deptList.size()>0){
    			user.setDeptId(deptList.get(0).getId());
    		}
    	}
        this.userMapper.updateById(user);
        return Message.success("修改用户成功啦!");
    }

    /**
               * 删除用户
     */
    @RequestMapping(value="delete")
    @ResponseBody
    @Logger(unit = LoggerModule.USER,type = LoggerType.DELETE)
    public Message delete(@RequestParam Integer id) {
        this.userMapper.deleteById(id);
        return Message.success();
    }
    
    /**
	     * 初始化密码
	*/
	@RequestMapping(value="initPwd")
	@ResponseBody
	public Message<String> initPwd(@RequestParam Integer id,@RequestParam String userCode) {
		User user = new User();
		user.setId(id);
		user.setPassword(MD5Pwd(userCode,initPwd));
		this.userMapper.updateById(user);
		return Message.success();
	}
    
    /**
     * 用户表单页面
     * @param model
     * @return
     */
    @RequestMapping(value = "assignRoles/{id}")
    public String authority(Model model,@PathVariable("id") int id) {
    	User user= userMapper.selectById(id);
    	model.addAttribute("id",id);
    	model.addAttribute("roleIds",user.getRoleIds());
    	return "system/user/assign_roles";
    }
    
    /**
     * 为角色授权菜单
     */
    @RequestMapping(value="assignRolesById")
    @ResponseBody
    public Message<String> assignRolesById(@RequestParam("roleIds") String roleIds, @RequestParam("id") int id) {
        userMapper.updateRoleIdByUserId(new User(id,roleIds));
        return Message.success();
    }
    
    /**
     * @description '新增用户'页面-用户账号前台验证-验证是否'登录账号'是否已存在，如果已存在则返回false并提醒用户换一个登录账号重新输入
     * 				'新增用户'页面向后台发出验证的请求地址为：/user/verifyUserCode?userCode=xxx
     * @param userCode
     * @return
     */
    @RequestMapping(value="verifyUserCode")
    @ResponseBody
    public Map verifyUserCode(String userCode){
    	User userObj=null;
    	Map<String,Boolean> map = new HashMap<String,Boolean>();
    	try {
    		//查询用户名是否在用户表中存在
    		userObj = userMapper.selectUserByLoginCode(userCode);
    		if (userObj == null) {
                map.put("valid", true);
            }else{
                map.put("valid", false);
            }
            return map;
    	}catch(Exception e) {
    		map.put("valid", false);
    		return map;
    	}
    }
    
    /**
     * @description '编辑用户'页面-用户账号前台验证,因为新增用户页面和编辑页面保持同样的书写风格,导致无法不得不编辑账号时也必须要验证，因为bootstrap-validator-obj.js内的if(list[i].id.indexOf("userCode") != -1是对凡是带有userCode输入域的账号重复性做验证，无法让某个页面可以重复性验证，也无法让某个页面不做重复性验证;也就是说要么一起都做重复性验证，要么都不做重复性验证!
     * 				'编辑用户'页面向后台发出验证的请求地址为：/user/edit/verifyUserCode?userCode=xxx  
     * @param userCode
     * @return
     */
    @RequestMapping(value="edit/verifyUserCode")
    @ResponseBody
    public Map editVerifyUserCode(String userCode){
    	Map<String,Boolean> map = new HashMap<String,Boolean>();
        map.put("valid", true);
        return map;
    }

}
